from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework import status
from rest_framework import views
from rest_framework import generics
from api.ownserializers import TbStrategySerializerHot, TbStrategySerializerDetail, TbStraregySerializerList
from common.models import TbStrategy, TbStyImg
from travel_guide.settings import BASE_DIR
import os


class PaginationSource(PageNumberPagination):
    """
    自定义rest_frame分页器，自定义分页样式！
    要创建自定义分页序列化程序类，　你应该子类化pagination.BasePaginatioon并覆盖pagnigate_queryset(self,queryset,request,view=None)和get_paginationed_response(self,data)方法：
    １　该pagination_queryset方法传递给初始查询集，　并且返回一个只包含请求页面中的数据的可迭代对象。
    ２　get_paginationed_response方法传递了序列化页面数据，　并返回一个Response实例。
    ×　注意　该paginationed_queryset方法可以在分页实例上设置状态，该状态稍后可以由该get_paginationed_response
    使用
    """
    page_size = 2
    page_query_param = 'page'
    page_size_query_param = 'size'


class TbStrategySourceHot(generics.ListAPIView):

    """
        基于通用视图的查询后人创建对象，list返回查询对象的列表，crate创建对象，
    基于通用视图的查询后人创建对象，list返回查询对象的列表，crate创建对象，
    在url调用的时候， 我们用视图类名.as_view()调用.
    """

    queryset = TbStrategy.objects.all().filter().order_by('views_count')[:4]
    serializer_class = TbStrategySerializerHot

    def list(self, request, *args, **kwargs):
            queryset = self.get_queryset()
            serializer = TbStrategySerializerHot(queryset, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)


class TbStrategyCitySource(generics.ListCreateAPIView):
    """
        基于通用视图的视图类，继承ListAPIView，返回查询对象的多个对象， 返回列表。
    我们用视图类名.as_view()调用.
    """

    queryset = TbStrategy.objects.all()
    serializer_class = TbStraregySerializerList

    def list(self, request, *args, **kwargs):
        city_id = request.GET.get('city')
        try:
            query_set = TbStrategy.objects.filter(dity_id=city_id)
            pager = PaginationSource()
            paged_query_set = pager.paginate_queryset(queryset=query_set, request=request, view=self)
            return pager.get_paginated_response(
                TbStraregySerializerList(paged_query_set, many=True).data)

        except Exception:
            return Response(status=status.HTTP_404_NOT_FOUND)

    def create(self, request, *args, **kwargs):

        """创建图片是实例，　用于用户上传图片文件"""

        try:
            serializer = TbStrategySerializerDetail(data=request.data)
            if serializer.is_valid(raise_exception=True):
                serializer.save()
                self.create_img(request, serializer.data['id'])
                return Response(serializer.data, status=status.HTTP_201_CREATED)

        except Exception:
            return Response(status=status.HTTP_404_NOT_FOUND)

    def create_img(self, request, id):

        try:
            files = request.FILES

            for key, value in files.items():

                file_path = os.path.join(BASE_DIR, 'static')
                file_name = os.path.join(file_path, 'strategy')
                image_name = os.path.join(file_name, str(value))
                with open(image_name, 'wb') as fp:
                    fp.write(value.read())
                TbStyImg.objects.create(name=value, url=image_name, sty_id=id)
            return Response(status=status.HTTP_201_CREATED)

        except Exception:
            return Response(status=status.HTTP_404_NOT_FOUND)


class TbStrategyDetailSource(views.APIView):

    """
        基于基本视图的视图类， 重写视图类的get方法，返回请求pk对应的模型的字段
    我们用视图类名.as_view()调用.
    """

    def get(self, request, pk, *args, **kwargs):
        try:
            serializer = TbStrategySerializerDetail(TbStrategy.objects.get(pk=pk))
            return Response(serializer.data, status=status.HTTP_200_OK)

        except Exception:
            return Response(status=status.HTTP_404_NOT_FOUND)

    def delete(self, pk, *args, **kwargs):

        try:
            strategy = TbStrategy.objects.get(pk=pk)
            strategy.delete()

        except Exception:
            return Response(status=status.HTTP_404_NOT_FOUND)
